/**
 * Created by shidaiapp on 2017/9/29.
 */
import actionUrls from "../../../../api/ApiUrls";
import ApiBase from "../../../../api/moudles/ApiBase";
import Vue from "vue";

function changeModelLoading(self, tiyData) {
  tiyData.tStatus.modalClear.isLoading = false;
  self.$nextTick(function () {
    tiyData.tStatus.modalClear.isLoading = true;
  });
}
/**
 * 初始化
 * @param self
 * @param tiyData
 */
export const init = (self, tiyData) => {
  //resetForm(self, tiyData);
  tiyData.tPage.total = 1;
  tiyData.tPage.startIndex = 0;
  tiyData.tPage.stepNumber = 40;
  tiyData.tPage.currentPage = 1;
  tiyData.tParams.userName = '';
  tiyData.tParams.startTime = "",
  tiyData.tParams.endTime = "",
  tiyData.tParams.orderBy = '';
  tiyData.tParams.selectedUsers= [];
  self.$ySpliceAll(tiyData.tData.userList, tiyData.tData.tabList);
  tiyData.tData.loginTypeDict = self.loginTypeDict;
  tiyData.tData.orderItemDict = self.orderItemDict;

  getTagList(self, tiyData);
 };


function getTagList(self, tiyData){
  let param = {
    "type": 2
  };

  self.$apiOther.queryManageTabs(param).then(function (response) {
    if(response.success){
      response.result.forEach(function(item){
        tiyData.tData.tabList.push(item);
      })
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * 清理操作记录
 * @param self
 * @param tiyData
 */
export const webClearOperationRecord = function (self, tiyData) {
  tiyData.tStatus.modalClear.isLoading = true;
  self.$apiRole.clearOperationRecord()
    .then(function (response) {
      tiyData.tStatus.modalClear.isShow = false;
      changeModelLoading(self, tiyData);
      if (response.success) {
        self.$Message.success('清除成功!');
      } else {
        tiyData.tStatus.modalClear.isLoading = false;
        self.$Message.error(response.errorMessage);
      }
    });
};


/**
 * 从服务器请求列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webList = (self, tiyData) => {
  if(tiyData.tParams.userName==''){
    self.$Message.error("请输入姓名/用户编号查询");
    return;
  }
  if(tiyData.tParams.tabId==undefined){
    tiyData.tParams.tabId='';
  }
  let data = {"pageSize": tiyData.tPage.stepNumber,
    "pageNum": tiyData.tPage.currentPage,
    "userName": tiyData.tParams.userName,
    "tabId": tiyData.tParams.tabId,
    "orderBy": tiyData.tParams.orderBy
  };
  //iview时间控件显示为utc时间，会转成本地时间，这里再转回来
  if(tiyData.tParams.startTime){
    data.startDate = Vue.prototype.$tiyQueryTime(new Date((tiyData.tParams.startTime).getTime()));
  }
  if(tiyData.tParams.endTime){
    data.endDate =  Vue.prototype.$tiyQueryTime(new Date((tiyData.tParams.endTime).getTime()));

  }
  self.$Spin.show();
  self.$apiUser.exactQueryUsers(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.userList.length = 0;
      let userPage = response.result;
      tiyData.tPage.total = userPage.total;
      tiyData.tPage.stepNumber = userPage.pageSize;
      userPage.list.forEach(
        function (item) {
          tiyData.tData.userList.push(item);
        }
      );
      if (0 == tiyData.tData.userList.length) {
        tiyData.tData.userList.splice(0,tiyData.tData.userList.length)
      }
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 从服务器请求订单列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webOrderList = (self, tiyData) => {
  self.$Spin.show();
  self.$apiUser.getUserOrders({
    "userId": tiyData.tParams.showOrder.userId,
    "pageNum": tiyData.tParams.showOrder.pageNum,
    "pageSize": tiyData.tParams.showOrder.pageSize
  }).then(function (response) {
    self.$ySpliceAll(tiyData.tData.orderList);
    self.$Spin.hide();
    if (response.success) {
      let orderPage = response.result;
      tiyData.tParams.showOrder.total = orderPage.total;
      orderPage.list.forEach(
        function (item) {
          tiyData.tData.orderList.push(item);
        }
      );
      tiyData.tStatus.modalOrder.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 从服务器请求购物车列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webCartList = (self, tiyData) => {
  self.$Spin.show();
  tiyData.tData.cartPriceCount = 0;
  tiyData.tData.cartWeightCount = 0;
  self.$apiUser.getShoppingCart({
    pageSize: tiyData.searchInfoPage.stepNumber,
    pageNum: tiyData.searchInfoPage.currentPage,
    userId: tiyData.tParams.showCart.userId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.cartList.splice(0,tiyData.tData.cartList.length);
      tiyData.searchInfoPage.total = response.result.data.total;
      tiyData.searchInfoPage.stepNumber = response.result.data.pageSize;
      let cartList = response.result.data.list;
      cartList.forEach(
        function (item) {
          tiyData.tData.cartList.push(item);
        }
      );
      tiyData.tData.cartWeightCount = response.result.sumWeight + 'g';
      tiyData.tData.cartPriceCount = '$' + response.result.sumPrice.toFixed(2);
      tiyData.tStatus.modalCart.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 从服务器请求用户地址列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webAddressList = (self, tiyData) => {
  self.$Spin.show();
  self.$apiUser.getUserAddress({
    "userId": tiyData.tParams.showAddress.userId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.addressList.length = 0;
      let userAddressesList = response.result;
      userAddressesList.forEach(
        function (item) {
          tiyData.tData.addressList.push(item);
        }
      );
      tiyData.tStatus.modalAddress.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 从服务器请求操作记录列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webRecordList = (self, tiyData) => {
  self.$Spin.show();
  self.$apiUser.getLoginRecords({
    "userId": tiyData.tParams.showRecord.userId,
    "pageNum": tiyData.tParams.showRecord.pageNum,
    "pageSize": tiyData.tParams.showRecord.pageSize,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.recordList.length = 0;
      let recordPage = response.result;
      tiyData.tPage.pageSize = recordPage.pageSize;
      tiyData.tParams.showRecord.total = recordPage.total
      recordPage.list.forEach(
        function (item) {
          tiyData.tData.recordList.push(item);
        }
      );
      tiyData.tStatus.modalRecord.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

export const userInfo = (self, tiyData,index) => {
  let user = tiyData.tData.userList[index];
  tiyData.tParams.showUserInfo=[];
  tiyData.tParams.showUserInfo.hasEmployee = (user.employee1Id != null) || (user.employee2Id != null); //有没有负责员工
  self.$Spin.show();
  self.$apiUser.getUserInfo({
    "userId": user.id,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let record = response.result;
      tiyData.tParams.showUserInfo.firstName=record.user.firstname;
      tiyData.tParams.showUserInfo.lastName=record.user.lastname;
      let way = '';
      self.loginTypeDict.forEach(function (item) {
        if (item.value == record.user.thirdParty) {
          way = item.name;
          return;
        }
      });
      tiyData.tParams.showUserInfo.thirdParty=way;

      let stateStr = '';
      self.$store.getters.dictionaries.userStateDict.forEach(function(item){
        if(item.value==record.user.state){
          stateStr = item.name;
          return;
        }
      });
      tiyData.tParams.showUserInfo.state=record.user.stateStr;
      tiyData.tParams.showUserInfo.country=record.user.countryName;
      tiyData.tParams.showUserInfo.phone=record.user.phone;
      tiyData.tParams.showUserInfo.isPushMessage=record.user.isPushMessage==1?true:false;
      tiyData.tParams.showUserInfo.isAdEmail=record.user.isAdEmail==1?true:false;

      if(record.user.tabList){
        tiyData.tParams.showUserInfo.tabList = [];
        record.user.tabList.forEach(function(item){
          tiyData.tParams.showUserInfo.tabList.push(item.id);
        });
      }

      if(record.extendInfo!=null){
        tiyData.tParams.showUserInfo.facebook=record.extendInfo.facebook;
        tiyData.tParams.showUserInfo.whatsapp=record.extendInfo.whatsapp;
        tiyData.tParams.showUserInfo.twitter=record.extendInfo.twitter;
        tiyData.tParams.showUserInfo.instagram=record.extendInfo.instagram;
        tiyData.tParams.showUserInfo.source=record.extendInfo.source;
        tiyData.tParams.showUserInfo.inviteCode=record.extendInfo.inviteCode;
        tiyData.tParams.showUserInfo.useContent=record.extendInfo.useContent;
      }

      tiyData.tParams.showUserInfo.employee1Id = record.user.employee1Id;
      tiyData.tParams.showUserInfo.employee2Id = record.user.employee2Id;
      tiyData.tParams.showUserInfo.userId = record.user.id;
      tiyData.tParams.showUserInfo.fullName = record.user.fullName;

      tiyData.tStatus.modalUserInfo.isShow=true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });

}

/**
 * 查询登录员工可以发放的优惠券模版
 * @param self
 * @param tiyData
 */
export const getCouponDefine = (self, tiyData) => {
  self.$Spin.show();
  self.$apiCoupon.getCouponDefineByEmployee({}).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let record = response.result;
      tiyData.tStatus.modalDistuibuteCoupon.couponDefines.splice(0, tiyData.tStatus.modalDistuibuteCoupon.couponDefines.length);
      if(record != null && record.length > 0){
        record.forEach(function (item) {
          tiyData.tStatus.modalDistuibuteCoupon.couponDefines.push(item);
        });
        tiyData.tStatus.modalDistuibuteCoupon.isShow=true;
      } else {
        self.$Message.error("没有可以发放的优惠券！");
      }
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * 发放优惠券
 * @param self
 * @param tiyData
 */
export const distributeCoupon = (self, tiyData) => {
  self.$Spin.show();
  let couponDefine = tiyData.tParams.selectedCoupon;
  let data = {"defineId":couponDefine.id,"title":couponDefine.title};
  let userIds = tiyData.tParams.selectedUsers;
  // tiyData.tParams.selectedUsers.forEach(function (item){
  //   userIds.push(item.id);
  // })
  data.userIds = userIds;
  self.$apiCoupon.distributeCoupon(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.info("优惠券发放成功！");
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * 查询当前员工负责的用户信息
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const queryUsersOfCurrentEmployee = (self, tiyData) => {
  if(tiyData.tParams.tabId==undefined){
    tiyData.tParams.tabId='';
  }
  let data = {"pageSize": tiyData.tPage.stepNumber,
    "pageNum": tiyData.tPage.currentPage,
    "orderBy": tiyData.tParams.orderBy,
    "tabId": tiyData.tParams.tabId,
  };
  //iview时间控件显示为utc时间，会转成本地时间，这里再转回来
  if(tiyData.tParams.startTime){
    data.startDate = Vue.prototype.$tiyQueryTime(new Date((tiyData.tParams.startTime).getTime()));
  }
  if(tiyData.tParams.endTime){
    data.endDate = Vue.prototype.$tiyQueryTime(new Date((tiyData.tParams.endTime).getTime()));
  }
  self.$Spin.show();
  self.$apiUser.queryUsersOfCurrentEmployee(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.userList.length = 0;
      let userPage = response.result;
      tiyData.tPage.total = userPage.total;
      tiyData.tPage.stepNumber = userPage.pageSize;
      userPage.list.forEach(
        function (item) {
          tiyData.tData.userList.push(item);
        }
      );
      if (0 == tiyData.tData.userList.length) {
        tiyData.tData.userList.splice(0,tiyData.tData.userList.length)
      }
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


/**
 * 查询当前员工负责的用户信息
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const assignUserToEmployee = (self, tiyData, isCurrentEmployee) => {
  let assignData = tiyData.tParams.assignUser;
  let message = "是否执行认领操作";
  if(!isCurrentEmployee){
    message = "是否执行分配操作"
  }
  self.$Modal.confirm({
    title: '确认',
    content: message,
    onOk: () => {
      self.$Spin.show();
      self.$apiUser.assignUserToEmployee(assignData).then(function (response) {
        self.$Spin.hide();
        if (response.success) {
          self.$Message.success("操作成功");
          tiyData.tStatus.modalUserInfo.isShow = false;
        } else {
          self.$Message.error(response.errorMessage);
        }
      });
    }
  });
};
